package com.updesignsz.admin.service;

import com.updesignsz.admin.mapper.*;
import com.updesignsz.commom.entity.User;
import com.updesignsz.commom.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 * Created User: lx
 * Date: 2020/4/28 14:26
 */
@Service
public class UserService {

    @Autowired private UserMapper userMapper;
    @Autowired private ModuleMapper moduleMapper;
    @Autowired private UserRoleMapper userRoleMapper;
    @Autowired private FunctionMapper functionMapper;
    @Autowired private RoleFunctionMapper roleFunctionMapper;


    public List<User> listAll() {
        return userMapper.listAll();
    }

    public User login (String username, String password) {
        return userMapper.login(username, password);
    }


    public List<String> getUserRoleModule(Integer userId) {
        List<String> list = new ArrayList<>();
        UserRole userRole = getUserRole(userId);
        if (userRole != null) {
            String functionIds = roleFunctionMapper.getRoleFunctionId(userRole.getRoleId());
            List<String> moduleList = functionMapper.getFunctionModuleList(functionIds);
            if (moduleList != null && moduleList.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (String moduleId : moduleList) {
                    sb.append(moduleId).append(",");
                }
                sb.deleteCharAt(sb.length() - 1);
                list.addAll(moduleMapper.findByModuleIdList(sb.toString()));
            }
        }
        return list;
    }


    public List<String> getUserRoleFunction(Integer userId) {
        List<String> list = new ArrayList<>();
        UserRole userRole = getUserRole(userId);
        if (userRole != null) {
            String functionIds = roleFunctionMapper.getRoleFunctionId(userRole.getRoleId());
            list.addAll(functionMapper.findByFunctionIdList(functionIds));
        }
        return list;
    }

    private UserRole getUserRole(Integer userId) {
        return userRoleMapper.getByUserId(userId);
    }




    public void saveUser(User user) {
        userMapper.saveUser(user);
        addUserRole(user);
    }

    public void updateUser(User user) {
        userMapper.updateUser(user);
        addUserRole(user);
    }

    public User getById(Integer id) {
        return userMapper.getById(id);
    }

    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
        userRoleMapper.deleteUserRoleByUserId(id);
    }


    private void addUserRole(User user) {
        if (user.getRoleIdList() != null && user.getRoleIdList().size() > 0) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(user.getRoleIdList().get(0));
            userRoleMapper.saveUserRole(userRole);
        }
    }
}
